import * as api from '@/services/adIpmoveConfig';
import type { ProColumns } from '@ant-design/pro-components';
import {
    EditableProTable,
} from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, {
    DrawerForm,
    ProFormSelect,
    ProFormDigit,
    ProFormText,
} from '@ant-design/pro-form';
import { Form, Button, Col, Divider, Row } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

type FormProps = {
    visible: boolean;
    current: API.AdIpmoveConfig | undefined;
    onCancel: () => void;
    onSubmit: (values: API.AdIpmoveConfig) => Promise<void>;
};

const Form2: React.FC<FormProps> = (props) => {
    const { visible, current, onCancel, onSubmit } = props;
    if (!visible) {
        return null;
    }

    const formRef = useRef<ProFormInstance>();

    const compareModeList = [
        { label: '等于', value: '=' },
        { label: '大于', value: '>' },
        { label: '大于等于', value: '>=' },
        { label: '小于', value: '<' },
        { label: '小于等于', value: '<=' }
    ];

    const getProductList = async () => {
        const result = await api.getProductList();
        if (result.success) {
            //console.log(result);

            let options: any[] = [];
            for (let item of result.data) {
                options.push({
                    label: item.productName,
                    value: item.id,
                });
            }
            setProductList(options);
        }
    };

    useEffect(() => {
        getProductList();
    }, []);

    const [productId, setProductId] = useState<number | undefined>(current?.productId);
    const [productList, setProductList] = useState<any[]>([]);

    const [areaFilterId, setAreaFilterId] = useState<number | undefined>(current?.areaFilterId);
    const [policyAreaList, setPolicyAreaList] = useState<any[]>([]);

    let defaultCurrent: Partial<API.AdIpmoveConfig> | undefined = undefined;
    if (!current) {
        defaultCurrent = {
            //areaFilterId: current?.areaFilterId || undefined,
        };
    }

    const [isFirst, setIsFirstd] = useState<boolean | undefined>(true);

    const loadAreaFilters = async (productId: number) => {
        const result = await api.getAreaFilterList({ productId: productId });

        console.log('loadAreaFilters: ', productId, result);

        if (result.success && result.data && result.data.length > 0) {
            let options: any[] = [];
            for (let item of result.data) {

                options.push({
                    label: item.areaName,
                    value: item.id,
                });
            }
            console.log(options);

            setPolicyAreaList(options);

            //如果首次的话设置第二个下拉框的值
            // console.log(isFirst);
            // if (isFirst) {
            //     form.setFieldValue('areaFilterId', current?.areaFilterId);
            //     setIsFirstd(false);
            // }

            //return Promise.resolve(options);
        } else {
            setPolicyAreaList([]);
        }
        // return Promise.resolve([]);

    };

    useEffect(() => {
        console.log(productId);
        if (productId) {
            formRef.current?.setFieldValue('areaFilterId', undefined);
            loadAreaFilters(productId);
        }
    }, [productId]);

    const handleFormSubmit = async (record: API.AdIpmoveConfig) => {
        console.log(record);

        record.config = JSON.stringify(dataSource);

        onSubmit(record);
    };

    let defaultDataSource: API.AdIpmoveConfigPolicy[] =
        current && current?.config.length > 2
            ? JSON.parse(current.config)
            : [];

    const [editableKeys, setEditableRowKeys] = useState<React.Key[]>(defaultDataSource.map((item) => item.id));
    const [dataSource, setDataSource] = useState<API.AdIpmoveConfigPolicy[]>(current?.config.length > 2 ? JSON.parse(current.config) : []);

    const columns: ProColumns<API.AdIpmoveConfigPolicy>[] = [
        {
            title: '平台',
            dataIndex: 'platform',
            width: 160,
            valueType: 'select',
            fieldProps: {
                options: productList,
            },
        },
        {
            title: '比较方式',
            dataIndex: 'compareMode',
            width: 120,
            valueType: 'select',
            fieldProps: {
                options: compareModeList,
            },
        },
        {
            title: '版本号',
            dataIndex: 'appVer',
            width: 80,
            valueType: 'digit',
            formItemProps: () => {
                return {
                    rules: [{ required: true, message: '请填写版本号比较方式' }],
                };
            },
        },
        {
            title: '漂移比例',
            dataIndex: 'ipMove',
            width: 80,
            valueType: 'digit',
        },
        {
            title: '操作',
            width: 80,
            valueType: 'option',
        },
    ];

    return (
        <DrawerForm<API.AdIpmoveConfig>
            formRef={formRef}
            open={visible}
            initialValues={current ? current : defaultCurrent}
            title={`${current ? '编辑' : '添加'}漂移配置`}
            width={1100}
            onFinish={handleFormSubmit}
            drawerProps={{
                onClose: onCancel,
                maskClosable: false,
            }}
        >
            <ProFormSelect
                name="productId"
                label="产品"
                options={productList}
                rules={[{ required: true, message: '请选择产品' }]}
                allowClear={false}
                fieldProps={{
                    onSelect: (value: number, options) => {
                        //console.log('value: ', value, ' options:', options);
                        setProductId(value);
                    },
                }}
            />
            <ProFormSelect
                name="areaFilterId"
                label="地区"
                options={policyAreaList}
                rules={[{ required: true, message: '请选择地区' }]}
                allowClear={false}
                fieldProps={{
                    onSelect: (value: number, options) => {
                        //console.log('value: ', value, ' options:', options);
                        setAreaFilterId(value);
                    },
                }}
            />
            <ProFormDigit
                name="ipMove"
                label="	漂移比例"
                min={0}
                max={9999}
                width={200}
                rules={[{ required: true }]}
            />

            <Row gutter={24}>
                <Col span={24}>
                    <Divider orientation="left" orientationMargin="0">
                        版本策略
                    </Divider>
                </Col>
                <Col span={24}>
                    <ProForm.Item>
                        <EditableProTable<API.AdIpmoveConfigPolicy>
                            rowKey="id"
                            recordCreatorProps={{
                                newRecordType: 'dataSource',
                                position: 'bottom',
                                record: () => ({
                                    id: `${Date.now()}`,
                                }),
                            }}
                            loading={false}
                            columns={columns}
                            defaultValue={dataSource}
                            request={async () => ({
                                data: dataSource,
                                success: true,
                            })}
                            value={dataSource}
                            onChange={(value: API.AdIpmoveConfigPolicy[]) => {
                                setDataSource(value);
                            }}
                            editable={{
                                type: 'multiple',
                                editableKeys: editableKeys,
                                actionRender: (row, config, defaultDom) => [
                                    //defaultDom.save,
                                    defaultDom.delete,
                                ],
                                onValuesChange: (record, recordList) => {
                                    //console.log(recordList);
                                    setDataSource(recordList);
                                },
                                onChange: setEditableRowKeys,
                            }}
                        />
                    </ProForm.Item>
                </Col>
            </Row>
        </DrawerForm>
    );
};

export default Form2;
